var storeServiceNative = require("../services/storeService.js");
var merchantServiceNative = require('../services/MerchantService');
var _ = require('underscore');
var async = require("async");
var errorHandler = require('../common/errorHandler');

module.exports = {
	index: function (req, res, next) {
		var merchantId = "";
		var sendData = {};
		var storeId = '';
		var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);
		var merchantService = errorHandler.errorToResponse(req, res, merchantServiceNative);
		async.series(
			[
				function (cb) {
					storeService.getStoreByDomainName(req.params.id, function (err, settings) {
						if (!settings) {
							return res.status(400).json({error: "该店铺没有开通微店铺"});
						}
						storeId = settings.store_id;
						sendData.settings = settings;
						cb(err, storeId);
					});
				},
				function (cb) {
					storeService.getStoreById(storeId, '', function (err, store) {
						if (err) {
							return res.status(500).send(err);
						}
						if (!store) {
							return res.status(500).send(err);
						}
						merchantId = store.merchant_id || store.MERCHANT_ID;
						sendData.store = store;
						cb(err, store);
					});
				},
				function (cb) {
					merchantService.getMerchantById(merchantId, function (err, data) {
						if (err) {
							return res.status(500).send(err);
						}
						sendData.merchant = data;
						cb(err, data);
					});
				}
			],
			function (err, result) {
				res.send(sendData);
			}
		);
	},
	getStoreConfig: function (req, res, next) {
		var sendData = {};
		var storeId = req.params.storeId;
		var key = req.query.key;
		var storeService = errorHandler.errorToResponse(req, res, storeServiceNative);
		async.series(
			[
				function (cb) {
					storeService.getStoreById(storeId, '', function (err, store) {
						if (err) {
							return res.status(500).send('');
						}
						if (!store) {
							return res.status(500).send('');
						}
						sendData.store = store;
						cb(err, store);
					});
				},
				function (cb) {
					storeService.getStoreConfig(storeId, key, function (err, config) {
						if (err) {
							return res.status(500).send(err);
						}
						if (!config) {
							return res.status(500).send(err);
						}
						sendData.config = config;
						cb(err, config);
					});
				}
			],
			function (err, result) {
				res.send(sendData.config);
			}
		);
	}
};
